package resources

import (
	"embed"
	"html/template"
	"reflect"

	"gitee.com/falling-ts/gower/app"
)

var (
	route = app.Route()
	Tmpl  *embed.FS
)

func init() {
	route.SetFuncMap(template.FuncMap{
		"assertAnySlice": func(v any) []any {
			switch reflect.TypeOf(v).Kind() {
			case reflect.Slice:
				val := reflect.ValueOf(v)
				result := make([]interface{}, val.Len())
				for i := 0; i < val.Len(); i++ {
					result[i] = val.Index(i).Interface()
				}
				return result
			default:
				return []any{}
			}
		},
		"safeHTML": func(html string) template.HTML {
			return template.HTML(html)
		},
		"getData": func(data map[string]any, field string, def any) any {
			if v, ok := data[field]; ok {
				return v
			}
			return def
		},
		"add": func(add int, added int) int {
			return add + added
		},
		"sub": func(sub int, subtracted int) int {
			return sub - subtracted
		},
		"pageShow": func(page int, currentPage int) bool {
			left := currentPage - 5
			right := currentPage + 5
			return left <= page && page <= right
		},
	})

	err := route.LoadHTMLGlobs(
		"resources/views/*.tmpl",
		"resources/views/**/*.tmpl",
		"resources/views/**/**/*.tmpl",
		"resources/views/**/**/**/*.tmpl",
	)
	if err != nil {
		if Tmpl == nil {
			panic("没有模板内容可加载")
		}
		route.LoadHTMLFS(Tmpl,
			"views/*.tmpl",
			"views/**/*.tmpl",
			"views/**/**/*.tmpl",
			"views/**/**/**/*.tmpl")
	}
}
